var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

//代理模块
var { createProxyMiddleware } = require('http-proxy-middleware');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var apiRouter = require('./routes/api');

var app = express();

//配置模版引擎
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
// app.use(express.urlencoded({ extended: false }));
// app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//应用级别中间件
 app.all('*', async function (req, res, next) {
    //设置爬虫请求头
    req.headers['user-agent'] = 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.3 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1 wechatdevtools/1.05.2204250 MicroMessenger/8.0.5 Language/zh_CN webview/16665764847122106 webdebugger port/39267 token/1568759fa6c96a6ab7b21af56a51741a';
    req.headers['cookie'] = 'Hm_lvt_7c356c0f35876d7ed6c4b4291873e46d=1666597574; ci_session=772dbfc2d087209768b19b2278f0d611d17bf7b9; NSC_xfdibu_xfc_wjq=ffffffff0975715845525d5f4f58455e445a4a423660; Hm_lpvt_7c356c0f35876d7ed6c4b4291873e46d=1666603555';
    req.headers['referer'] = 'http://wx.kia.cn/h5/organize-coupons/client/index.html';
    req.headers['host'] = 'wx.kia.cn';
    req.headers['origin'] = 'http://wx.kia.cn';
    req.headers['content-type'] = 'application/json;charset=UTF-8';
    console.log(req.headers,1)

    // 设置允许跨域的域名,*代表允许任意域名跨域
    res.header('Access-Control-Allow-Origin','*');
    // 允许的header类型
    res.header('Access-Control-Allow-Headers','content-type');
    // 跨域允许的请求方式
    res.header('Access-Control-Allow-Methods','DELETE,PUT,POST,GET,OPTIONS');

    next();
});

app.use('/', indexRouter);
app.use('/users', usersRouter);


app.use('/api', createProxyMiddleware({
  target: 'http://wx.kia.cn', // 这一行是服务端地址
  changeOrigin: true,
  pathRewrite: {
    '^/api': '' // 在向服务端发起请求时，去掉标识xhr的前缀
  }
}));




// catch 404 and forward to error handler
app.use(function(req, res, next) {
    next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});


module.exports = app;